import numpy as np



def getBatchData(batchSize):
    # 使用 NumPy 生成假数据(phony data), 总共 100 个点.
    x_data = np.float32(np.random.rand(batchSize,3))  # 随机输入
    y_data = np.dot([0.100, 0.5, 0.6], np.transpose(x_data)) + 3

    #数据预处理 对偏置值 定义xb ，假定x=1
    b = np.ones(batchSize)
    b.astype(np.float32)
    xc = np.c_[x_data,b]
    return xc,y_data


class Model:
    def __init__(self):
        self.wcount = 4
        self.batchSize = 100
        self.theta = np.float32(np.random.rand(self.wcount))
        self.rate = 0.001

    def forward(self, x):
        y1 = np.dot(self.theta, np.transpose(x))
        return y1

    def cost(self, y, py):
        cost = np.sum((py - y) ** 2) / (self.batchSize * 2)
        return cost

    def gradientDescent(self, x, y, y1):
        yt = y1 - y
        for j in range(self.wcount):
            d1 = np.sum(yt * x[:, j]) / self.batchSize
            self.theta[j] = self.theta[j] - self.rate * d1

    def train(self,iteration):
        x_data,y_data=getBatchData(self.batchSize)
        for i in range(iteration):
            y1 = model.forward(x_data)
            d = model.cost(y_data, y1)
            model.gradientDescent(x_data, y_data, y1);
            if i % 100 == 0:
                print("step:{},cost:{}".format(i, d))


model = Model()
model.train(100000)

print(model.theta)
